package tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class FileTools {
	/**
	 * 写入文件
	 * @param file_name  文件名
	 * @param content    写入内容
	 * @param append    false 覆盖  true 追加
	 */
	public static void WriteFile(String file_name,String content,boolean append){
		BufferedWriter bw = null;
		try{
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file_name,append)));
			bw.write(content);
			//bw.newLine();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally {
			try {
				bw.flush();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}

	 /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     * 该方法读取原始登陆日志
     */
    public static List<String> readFileByLines(String fileName) {
    	List<String> al = new ArrayList<String>();
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
            	al.add(tempString.trim());
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return al;
    }

    /**
     * 将日志按每份count条数据放入List中
     * @param content
     * @param count
     * @return
     */
    public static List<List<String>> cleanList(List<String> content,int count){
    	List<List<String>> cleanList = new ArrayList<List<String>>();
    	int a = count;
    	int size = content.size();
		int m = size%a==0?size/a:size/a+1;
		for(int i=0;i<m;i++){
			List<String> list = new ArrayList<String>();
			for(int j=i*a;j<=i*a+(a-1);j++){
				if(j<=size-1){
					list.add(content.get(j));
				}else{
					break;
				}
			}
			cleanList.add(list);
		}
		return cleanList;
    }
}
